import {loginPass, logout, register} from "@/api/auth.js";
import {getToken, getUserName, removeToken, setToken, setUserName} from "@/utils/auth.js";
import {router} from "@/main.js";

const user = {
    state : {
        token: getToken(),
        name: '',
        avatar: '',
        introduction: '',
        roles: [],
        count: 0,
        pv: 0,
        username: getUserName()

    },
//更改state的mutation，只能进行同步
    mutations : {
        SET_TOKEN: (state, token) => {
            state.token = token
            setToken(token)
        },
        SET_INTRODUCTION: (state, introduction) => {
            state.introduction = introduction
        },
        SET_USERNAME: (state, username) => {
            state.username = username
            setUserName(username)
        },
        SET_NAME: (state, name) => {
            state.name = name
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles
        },
        COUNT: (state) => {
            state.count++
        },
        increment(state) {
            state.count++
        },
        login_count(state) {
            state.pv++
        },
        userinfo(state, payload) {
            state.username = payload.username
        }
    },

//包含了mutations的action，可以使用异步
    actions : {

        async asyncLogin({commit}, userInfo) {
            console.log('userinfo:', userInfo)
            const {username, password} = userInfo
            return loginPass({username: username.trim(), password: password})
        },

        login2({commit}, userInfo) {
            const {username, password} = userInfo
            return loginPass({username: username.trim(), password: password})
        },

        login({commit},userInfo) {
            const {username, password} = userInfo
            return new Promise((resolve, reject) => {
                loginPass({username: username.trim(), password: password}).then(res => {
                    const {data} = res
                    console.log('res data > ', data)
                    if (data.code === 200) {
                        commit('SET_TOKEN', data.data.token)
                        commit('SET_USERNAME', username.trim())
                        setToken(data.data.token)
                        layer.msg('登陆成功')
                        router.push('/')
                        resolve()
                    } else {
                        layer.msg(data.data)
                    }
                }).catch(e => {
                    console.log('e > ', e)
                    resolve()
                })
            })
        },

        Register({commit}, userInfo) {
            return new Promise((resolve, reject) => {
                register(userInfo).then(res => {
                    const {data} = res
                    console.log('res data > ', data)
                    if (data.code === 200 && data.data) {
                        layer.msg('注册成功')
                        setTimeout(() => {
                            router.push('/signIn')
                        }, 1000);
                    } else {
                        layer.msg(data.message)
                    }
                    // commit('SET_TOKEN',data.token)
                    // setToken(data.token)
                    resolve()
                })
            })
        },


        Logout({commit}) {
            console.log('logout')
            logout().then(r => {
                console.log('logout res ', r.data);
                commit('SET_TOKEN', '')
                commit('SET_ROLES', [])
                removeToken()
                location.reload()
                router.push('/')
            })

            // return new Promise((resolve, reject) => {
            //     logout().then(() => {
            //         commit('SET_TOKEN', '')
            //         commit('SET_ROLES', [])
            //         removeToken()
            //         // resetRouter()
            //         // reset visited views and cached views
            //         // dispatch('tagsView/delAllViews', null, { root: true })
            //         resolve()
            //     }).catch(error => {
            //         reject(error)
            //     })
            // })
        },

        increment({commit}) {
            commit('increment')
        },
        login_count({commit}) {
            commit('login_count')
        }
    },

    getters : {
        token: state => state.token,
        avatar: state => state.avatar,
        name: state => state.name,
        username: state => state.username,
        introduction: state => state.introduction,
        roles: state => state.roles,
    }
}

export default user
